package com.example.disk.controller;


import com.example.disk.domain.entity.User;
import com.example.disk.service.FileService;
import com.example.disk.service.UserService;
import com.example.disk.util.Email_Util;
import com.example.disk.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author auto
 * @since 2020-07-15
 */
@Controller
@ResponseBody
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;
    @Autowired
    FileService fileService;

    //接收邮件请求

    /*
    * 功能：发送验证码
    * 完成时间：7.16 14:03
    * 完成人：李帅
    * */

    @RequestMapping(value = "/email")
    public Response getEmail(String email, HttpSession session){

        boolean hasEmail = userService.hasEmail(email);
        if(!hasEmail){ //没注册就查询该email是否有效，若无效，则返回此email已经注册
            //生成6位数随机数验证码

            int captcha = (int)(Math.random()*100000);
            System.out.println(captcha);
            boolean flag = Email_Util.send(email,captcha);
            if(flag){   //如果没注册且存在就像用户发送验证码，将验证码、邮箱存在session中
                session.setAttribute("captcha",captcha);
                session.setAttribute("email",email);
                return Response.build().setCode(200).setMsg("验证码已经发送，请注意查收");
            }else{  //email不存在
                return Response.build().setCode(400).setMsg("该邮箱非法，请检查邮箱输入是否正确");
            }

        }else{  //注册了就返回已经注册
            return Response.build().setCode(400).setMsg("该邮箱已经注册");
        }

    }


    /*
    * 功能：注册
    * 完成人：李帅
    * 完成时间：7.16 16:22
    * */
    @RequestMapping("/register")
    public Response register(User user,String captcha,HttpSession session){

        boolean hasUsername = userService.hasUsername(user.getUsername());
        if(hasUsername){      //账号已经注册，通知前端账号已经注册
            return Response.build().setCode(400).setMsg("账号已经注册");
        }else{  //账号没有注册 检查邮箱账号是否改动
            String last_email = (String) session.getAttribute("email");
            if(user.getEmail().equals(last_email)){   //邮箱没有改动 检查验证码是否正确
                int last_code = (int)session.getAttribute("captcha");
                if(last_code==Integer.parseInt(captcha)){   //验证码正确  在数据库中创建该用户信息 在obs中创建用户的文件夹
                    user.setImg("");
                    user.setCreateTime(LocalDateTime.now());
                    user.setUpdateTime(LocalDateTime.now());
                    user.setSize(1024*1024*1024);
                    user.setUsedSize(0);
                    userService.insertOne(user);
                    session.setAttribute("captcha",0);      //使验证码失效

                    //数据库和obs中创建根目录文件夹
                    fileService.createRoot(user.getUsername(),userService.getUserInfoByUserName(user.getUsername()).getId());
                    return Response.build().setCode(200).setMsg("注册成功");

                }else{  //验证码输入错误
                    return Response.build().setCode(400).setMsg("验证码输入错误");
                }
            }else{  //邮箱改动了
                return Response.build().setCode(400).setMsg("邮箱与之前的输入不符合");
            }
        }
    }


    /*
     * 功能：登录
     * 完成人：李帅
     * 完成时间：7.16 18:04
     * */
    @RequestMapping("/login")
    public Response login(String username,String password,HttpSession session){

        //判断账号和密码是否输入正确
        boolean flag = userService.hasUserNameAndPsw(username,password);
        if(flag){//存在该账号 取相关信息
            User user = userService.getUserInfoByUserName(username);
            //创建返回信息
            Map<String,Object>data = new HashMap<>();
            data.put("userId",user.getId());
            data.put("username",user.getUsername());
            data.put("userImgUrl",user.getImg());
            data.put("userInfoObj","");
            data.put("nickname",user.getNickname());

            //session中存储相关值
            session.setAttribute("login",true);
            session.setAttribute("userId",user.getId());
            session.setAttribute("username",user.getUsername());
            return Response.build().setCode(200).setMsg("登录成功").setData(data);
        }else{//不存在该账号
            return Response.build().setCode(400).setMsg("输入的账号或者密码有误");
        }
    }


    /*
     * 功能：获取登录后的信息
     * 完成人：李帅
     * 完成时间：7.16 21:04
     * */

    @RequestMapping("/userlogininfo")
    public Response getLoginInfo(HttpSession session){
        boolean login;
        try{
            login = (boolean)session.getAttribute("login");
        }catch (NullPointerException e){
            login=false;
        }

        if(login){
            String username = (String)session.getAttribute("username");
            User user = userService.getUserInfoByUserName(username);
            //创建返回信息
            Map<String,Object>data = new HashMap<>();
            data.put("userId",user.getId());
            data.put("username",user.getUsername());
            data.put("userImgUrl",user.getImg());
            data.put("userInfoObj","");
            data.put("nickname",user.getNickname());

            return Response.build().setCode(200).setMsg("获取值成功").setData(data);
        }
        return Response.build().setCode(400).setMsg("该账号未登录");
    }

    @RequestMapping("logout")
    public Response logout(HttpSession session) {
        session.invalidate();
        return Response.build().setCode(200).setMsg("退出成功");
    }

    //修改信息  映射待定
    public void reviseInfo(String nickname, String password, String ensure_password, MultipartFile file,HttpSession session) throws IOException {
        String username = session.getAttribute("username").toString();
        //上传头像到obs
        fileService.saveFile(username,"/",file,"my_head_photo.jpg");        //待定
        //得到url，设置用户img属性

        //修改用户数据库
    }
}
